(function($) {
    $(function(event) {
        if ($('div.layout-container').length) {
            $('#edit_page').one('click', function() {
                removePageForm();
                displayPageForm($(this).metadata().page_id);
                return false;
            });
            setLayout($('div.layout-container').metadata().layout_id);
            if (!$('div.layout-container').metadata().page_id) {
                removePageForm();
                displayPageForm();
            }
        }
        $('a.lnk-set-menu-order').click(function(){
            setMenuOrder();
        });
        bindBlockEvents();
        menuSortable();
        inputFileOver();
        bindLogoEvents();
    });
})(jQuery);

layouts = {
    1 : 'simple',
    2 : 'col-right',
    3 : 'col-left',
    4 : 'col-left-right',
    5 : 'top-bottom-col-left-right',
    6 : 'top-col-right',
    7 : 'top-col-left',
    8 : 'top-col-left-right'
};
function setLayout(id) {
    $('div.controls a.back_block').click();
    $('div.layout').hide();
    $('#' + layouts[id]).show();
}

function displayPageForm(pageId) {
    $.post("/a_ajax/customization.getPageFormContent", 'page_id=' + pageId, displayPageFormCallback, "json");
    function displayPageFormCallback(resp, textStatus) {
        if (!resp.error) {
            $('#admin-top-menu').after(resp.data);
            $('#page-edit').show();
            $('#admin-top-menu ul.ctrls li a.slide-down').parents('li').addClass('active');
            bindBorderSetter();
            bindPageFormEvents();
            $('ul.templates li.tpl-' + $('#page_layout_id').val() + ' a').click();
        }
        else {
            alert(resp.error);
        }
    }
}

function removePageForm() {
    $('#page-edit').remove();
}

function postPageForm() {
    customPageBlockAsync = false;
    $('div.controls a.ok_custom_block:visible').click();
    customPageBlockAsync = true;
    req = {
        'page_id'               : $('#page_id').val(),
        'page_title'            : $('#page_title').val(),
        'page_menu_name'        : $('#page_menu_name').val(),
        'page_meta_description' : $('#page_meta_description').val(),
        'page_meta_keywords'    : $('#page_meta_keywords').val(),
        'page_layout_id'        : $('#page_layout_id').val()
    };
    action = "/a_ajax/customization." + ($('#page_id').val() ? "update" : "add");
    $.post(action, req, addPageCallback, "json");
    function addPageCallback(resp, textStatus) {
        if (!resp.error) {
            document.location = '/a_static?page_id=' + resp.data.pageId;
        }
        else {
            alert(resp.error);
        }
    }
}

function deletePage(pageId) {
    req = {
            'page_id' : pageId
        };
    $.post("/a_ajax/customization.delete", req, deletePageCallback, "json");
    function deletePageCallback(resp, textStatus) {
        if (!resp.error) {
            if (resp.data.newPageId) {
                document.location = '/a_static?page_id=' + resp.data.newPageId;
            }
            else {
                document.location = '/';
            }
        }
        else {
            alert(resp.error);
        }
    }
}

function bindPageFormEvents() {
    $('#save_page_form').click(function(){
        postPageForm();
        return false;
    });
    $('#cancel_page_form').click(function(){
        location.href="/";
        removePageForm();
        return false;
    });
    $('#del_page').click(function() {
        if (confirm('Удалить страницу?')) {
            deletePage($('#page_id').val());
        }
        return false;
    });
    bindLayoutEvents();
}
function bindBlockEvents() {
    $('div.controls a.edit_block').click(function() {
        editBlock($(this).metadata().block_id);
        return false;
    });
    $('div.controls a.back_block').click(function() {
        backBlock($(this).metadata().block_id);
        block.resize.destroy($(this).metadata().block_id);
        return false;
    });
    $('div.controls a.ok_custom_block').click(function() {
        var thisOuterBlock = $(this).parents('form.editable');
        saveCustomPageBlock($(this).metadata().block_id, thisOuterBlock);
        block.resize.destroy($(this).metadata().block_id);
        return false;
    });
    $('div.controls a.ok_block').click(function() {
        var thisOuterBlock = $(this).parents('form.editable');
        saveBlock($(this).metadata().block_id, thisOuterBlock);
        block.resize.destroy($(this).metadata().block_id);
        return false;
    });
}
function bindLogoEvents() {
    $('.handler-del-logo').click(function(){
        if (!confirm('Удалить логотип?')) {
            return false;
        }
    });
	/*
    $('.handler-upload-logo').click(function(){
    	form = $(this).parents('form');
    	form.find('input.no_logo_save').val(1);
    	form.submit();
    	return true;
    });
	*/
    $('.handler-save-logo').click(function(){
    	/*$(this).parents('form').submit();
    	return false;*/
    	form = $(this).parents('form');
    	form.submit();
    	return false;
    });
}

function setPageFormLayout(layoutId) {
    $('#page_layout_id').val(layoutId);
}

function backBlock(blockId) {
    $('#' + blockId + ' div.controls a.edit').show();
    $('#' + blockId + ' div.controls a.ok').hide();
    $('#' + blockId + ' div.controls a.back').hide();
    $('#' + blockId + ' div.controls h2:first').hide();
    if ($('#' + blockId     + ' div.controls input').val().length > 0) {
        $('#' + blockId + ' div.controls h2:last').show();
    }
    $('#' + blockId + ' div.content').show();
    showEditor(blockId, false);
}

function editBlock(blockId) {
    $('#' + blockId + ' div.controls a.edit').hide();
    $('#' + blockId + ' div.controls a.ok').show();
    $('#' + blockId + ' div.controls a.back').show();
    $('#' + blockId + ' div.controls input').show();
    $('#' + blockId + ' div.controls h2:first').show().css('overflow', 'visible');
    $('#' + blockId + ' div.controls h2:last').hide();
    $('#' + blockId + ' div.content').hide();
    if (!isEditorExists(blockId)) {
    	startEditor(blockId);
    }
	showEditor(blockId, true);
    block.resize.init(blockId);
}

function okBlock(blockId) {
    backBlock(blockId);
    $('#' + blockId + ' div.controls h2:last').text($('#' + blockId + ' div.controls input').val());
    if ($('#' + blockId + ' div.controls input').val().length <= 0) {
        $('#' + blockId + ' div.controls h2:last').hide();
    }
    $('#' + blockId + ' div.content').html(getEditorContent(blockId));
}

function startEditor(blockId) {
    Xinha.startEditors(Xinha.makeEditors(['editor-' + blockId], xinha_config, xinha_plugins));
}

function linksBindClick(e) {
	e.preventDefault();
	//e.stopPropagation();
	var thisHref = $(this).attr('href');
	if (confirm('Сохранить изменения?')) {
		customPageBlockAsync = false;
		var blockId;
		while (openedBlocks.length > 0) {
			blockId = openedBlocks[0];
			if ($('div.layout-container').length) {
				saveCustomPageBlock(blockId, $('#' + blockId + ' form.editable'));
			}
			else {
				saveBlock(blockId, $('#' + blockId + ' form.editable'));
			}
			block.resize.destroy(blockId);
		}
		customPageBlockAsync = true;
		location.href = thisHref;
		return false;
	} else {
		location.href = thisHref;
	}
};
function bindConfirmSaveEvent() {
	return; // does not work correctly now
	if (openedBlocks.length > 0) {
		$('a').not('.ok_block ctrl').not('.ok_custom_block ctrl').not('.back_block ctrl').not('.edit_block ctrl').click(linksBindClick);
		$('table.htmlarea a').unbind('click', linksBindClick);
	}
	else {
		$('a').unbind('click', linksBindClick);
	}
}

openedBlocks = [];
function showEditor(blockId, show) {
    if (show) {
    	openedBlocks.push(blockId);
    	bindConfirmSaveEvent();
        $('#' + blockId + ' table.htmlarea').show();
    }
    else {
    	tmpArr = [];
    	for (i=0; i<openedBlocks.length; i++) {
    		if (openedBlocks[i] != blockId) {
    			tmpArr.push(openedBlocks[i]);
    		}
    	}
    	openedBlocks = tmpArr;
    	bindConfirmSaveEvent();
        $('#' + blockId + ' table.htmlarea').hide();
    }
}

function getEditorContent(blockId) {
    return Xinha.getEditor('editor-' + blockId).getEditorContent();
}

function setEditorContent(blockId, content) {
    Xinha.getEditor('editor-' + blockId).setEditorContent(content);
}

function isEditorExists(blockId) {
    return $('#' + blockId + ' table.htmlarea').length > 0;
}

customPageBlockAsync = true;
function saveCustomPageBlock(blockId, thisOuterBlock) {
    thisOuterBlock.find('a.back_block').after('<img id="ajax_loader_1" src="/i/ajax-loader-small.gif" alt="" style="float:right; margin:1px 10px 0 0;" />');
    req = {
        'block_page_id' : $('div.layout-container').metadata().page_id,
        'block_id'      : blockId,
        'block_title'   : $('#' + blockId + ' div.controls input').val(),
        'block_content' : getEditorContent(blockId)
    };
    $.ajax({
        async    : customPageBlockAsync,
        type     : "POST",
        url      : "/a_ajax/customization.saveCustomPageBlock",
        dataType : "json",
        data     : req,
        success: function(data){
            thisOuterBlock.find('#ajax_loader_1').remove();
            savePageBlockCallback(data);
            bindLightBox();
        }
    });
    function savePageBlockCallback(resp) {
        if (!resp.error) {
            $('#page_id').val(resp.data.pageId);
            /*$('#' + blockId + ' div.controls input').val(data[1]);*/
            setEditorContent(blockId, resp.data.content);
            okBlock(blockId);
        }
        else {
            alert(resp.error);
        }
    }
}

function saveBlock(blockId, thisOuterBlock) {
    req = {
        'block_id'      : blockId,
        'block_title'   : $('#' + blockId + ' div.controls input').val(),
        'block_content' : getEditorContent(blockId)
    };
    thisOuterBlock.find('a.back_block').after('<img id="ajax_loader_1" src="/i/ajax-loader-small.gif" alt="" style="float:right; margin:1px 10px 0 0;" />');
    $.ajax({
        async    : customPageBlockAsync,
        type     : "POST",
        url      : "/a_ajax/customization.updateBlock",
        dataType : "json",
        data     : req,
        success: function(resp){
    		saveBlockCallback(resp);
        }
    });
    function saveBlockCallback(resp, textStatus) {
        if (!resp.error) {
            /*$('#' + blockId + ' div.controls input').val(data[0]);*/
            setEditorContent(blockId, resp.data.content);
            okBlock(blockId);
            thisOuterBlock.find('#ajax_loader_1').remove();
            bindLightBox();
        }
        else {
            alert(resp.error);
        }
    }
}

function bindLayoutEvents() {
    $(function() {
        $('ul.templates li a').click(function() {
            $('ul.templates li').removeClass('active');
            $(this).parents('li').addClass('active');
        });
        $('ul.templates li.tpl-1 a').click(function() {
            setLayout(1);
            setPageFormLayout(1);
        });
        $('ul.templates li.tpl-2 a').click(function() {
            setLayout(2);
            setPageFormLayout(2);
        });
        $('ul.templates li.tpl-3 a').click(function() {
            setLayout(3);
            setPageFormLayout(3);
        });
        $('ul.templates li.tpl-4 a').click(function() {
            setLayout(4);
            setPageFormLayout(4);
        });
        $('ul.templates li.tpl-5 a').click(function() {
            setLayout(5);
            setPageFormLayout(5);
        });
        $('ul.templates li.tpl-6 a').click(function() {
            setLayout(6);
            setPageFormLayout(6);
        });
        $('ul.templates li.tpl-7 a').click(function() {
            setLayout(7);
            setPageFormLayout(7);
        });
        $('ul.templates li.tpl-8 a').click(function() {
            setLayout(8);
            setPageFormLayout(8);
        });
    });
}

function menuSortable() {
    $('#menu-sort-list').sortable({
        handle: '.move',
        opacity: 0.5,
        update: function() {
            var result = $('#menu-sort-list').sortable('toArray');
            for (var i = 0; i < result.length; i++) {
                result[i] = result[i].replace(/list_/i, '');
            }
            $('input[name="menu_page_order"]').val(result);
        }
    });
}

function setMenuOrder() {
    order = $('#menu_page_order').val();
    if (!order) {
        return;
    }
    $.post("/a_ajax/customization.setMenuOrder", 'order=' + order, setMenuOrderCallback, "json");
    function setMenuOrderCallback(resp, textStatus) {
        if (!resp.error) {
            $('#admin-top-menu').html(resp.data);
//            alert('Порядок меню изменен');
        }
        else {
            alert(resp.error);
        }
    }
}

function inputFileOver() {
    $('input.file').change(function() {
        $(this).parents('.file-outer').find('input.overinput').val(this.value);
    });
}

// Vertical resizing a block

var block = {};

block.resize = {
    init: function(blockId) {
        if (!$.browser.msie) {
            block.resize.setAfterBlock(blockId);
        }
    },
    setAfterBlock: function(blockId) {
        var $this = $('#' + blockId + ' .block-resize');
        $this.append('<div class="setHeightControls"><a class="less disabled" href="javascript:void(0)" title="Уменьшить окно"></a><a class="more" href="javascript:void(0)" title="Увеличить окно"></a></div>');
        $this.find('.setHeightControls a.more').bind('click', block.resize.moreClick);
        $this.find('.setHeightControls a.less').bind('click', block.resize.lessClick);
    },
    moreClick: function(e) {
        var h = $(e.target).parents('.block-resize').find('table.htmlarea iframe.xinha_iframe').height();
        var dh = 100;
        $(e.target).parents('.block-resize').find('.setHeightControls a.less').bind('click', block.resize.lessClick);
        if ($(e.target).siblings('.less').hasClass('disabled')) {
            $(e.target).siblings('.less').removeClass('disabled');
        };
        $(e.target).parents('.block-resize').find('table.htmlarea iframe.xinha_iframe').height(h+dh);
    },
    lessClick: function(e) {
        var h = $(e.target).parents('.block-resize').find('table.htmlarea iframe.xinha_iframe').height();
        var dh = 100;
        if (h < 3*dh) {
            $(e.target).parents('.block-resize').find('div.setHeightControls a.less').addClass('disabled');
        }
        if (h < 2*dh) {
            dh = 0;
            block.resize.unbindLessClick(e.target);
            $(e.target).parents('.block-resize').find('table.htmlarea iframe.xinha_iframe').height(h);
        } else {
            $(e.target).parents('.block-resize').find('table.htmlarea iframe.xinha_iframe').height(h-dh);
        }
    },
    unbindLessClick: function(elm) {
        $(elm).unbind('click', block.resize.lessClick);
    },
    destroy: function(blockId) {
        $('#' + blockId + ' .block-resize .setHeightControls a.more').unbind('click', block.resize.moreClick);
        $('#' + blockId + ' .block-resize .setHeightControls a.less').unbind('click', block.resize.lessClick);
        $('#' + blockId + ' .block-resize div.setHeightControls').remove();
    }
}
